<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
    <title>@lang{Elfinder文件管理器-2.1.6}</title>

    <js:part name="escape-unescape-string"/>
    <js:part name="file-size-to-string"/>
    <!-- Require JS (REQUIRED) -->
    <!-- Rename "main.default.js" to "main.js" and edit it if you need configure elFInder options or any things -->
    <script data-main="{{main_js}}"
            src="@static(Weline_Backend::backend/lib/requirejs/2.3.6/requirejs.min.js)"></script>
    <script>
        var $ = parent.$;
        const urlParams = {};
        let search = decodeURIComponent(window.location.search);
        search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(match, key, value) {
            urlParams[key] = value;
        });
        let startPath = urlParams.startPath;
        let targetId = null;
        if(urlParams.target){
            targetId = '#'+urlParams.target;
        }
        let closeId = null;
        if(urlParams.close){
            closeId = '#'+urlParams.close;
        }
        let preview = urlParams.preview;
        let multi = urlParams.multi;
        let ext = urlParams.ext;
        let size = urlParams.size;
        let setAttr = urlParams.setAttr;
        define('elFinderConfig', {
            // elFinder options (REQUIRED)
            // Documentation for client options:
            // https://github.com/Studio-42/elFinder/wiki/Client-configuration-options
            defaultOpts: {
                cssAutoLoad: ['themes/windows-10/css/theme.css'],
                url: '@backend-url("*/backend/connector")?startPath=' + startPath+'&ext='+ext+'&size='+size+'&multi='+multi, // or connector.maximal.php : connector URL (REQUIRED)
                commandsOptions: {
                    getfile: {multiple: true},
                    edit: {
                        extraOptions: {
                            // set API key to enable Creative Cloud image editor
                            // see https://console.adobe.io/
                            creativeCloudApiKey: '',
                            // browsing manager URL for CKEditor, TinyMCE
                            // uses self location with the empty value
                            managerUrl: ''
                        }
                    },
                    quicklook: {
                        // to enable CAD-Files and 3D-Models preview with sharecad.org
                        sharecadMimes: ['image/vnd.dwg', 'image/vnd.dxf', 'model/vnd.dwf', 'application/vnd.hp-hpgl', 'application/plt', 'application/step', 'model/iges', 'application/vnd.ms-pki.stl', 'application/sat', 'image/cgm', 'application/x-msmetafile'],
                        // to enable preview with Google Docs Viewer
                        googleDocsMimes: ['application/pdf', 'image/tiff', 'application/vnd.ms-office', 'application/msword', 'application/vnd.ms-word', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/postscript', 'application/rtf'],
                        // to enable preview with Microsoft Office Online Viewer
                        // these MIME types override "googleDocsMimes"
                        officeOnlineMimes: ['application/vnd.ms-office', 'application/msword', 'application/vnd.ms-word', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.spreadsheet', 'application/vnd.oasis.opendocument.presentation']
                    }
                },

                getFileCallback: function (file, fm) {
                    // 大小限制
                    if (size) {
                        for (let i = 0; i < file.length; i++) {
                            let f = file[i];
                            let f_size = parseInt(f.size);
                            if (f_size > size) {
                                throw new Error('@lang{文件超过大小限制。必须小于：}' + fileSizeToString(size) + ' @lang{当前大小：}' + fileSizeToString(f.size));
                            }
                        }
                    }
                    if (ext !== '*') {
                        let ext_ = ext.split(',').map(function (e) {
                            return e.trim();
                        })
                        for (let i = 0; i < file.length; i++) {
                            let f = file[i];
                            let fExt = f.name.split('.').pop().toLowerCase();
                            let allow = false;
                            for (let i = 0; i < ext_.length; i++) {
                                if (fExt === ext_[i]) {
                                    allow = true;
                                }
                            }
                            if (!allow) {
                                throw new Error('@lang{文件类型错误。仅支持的文件类型有：}' + ext_.join(', '));
                            }
                        }
                    }
                    let isMulti = true;
                    if (multi === 0 || multi === '0' || multi === 'false' || multi === undefined || multi === null) {
                        isMulti = false;
                    }
                    if (file.length > 1 && !isMulti) {
                        file.splice(0, file.length - 1)
                    }
                    var urls = $.map(file, function (f) {
                        return decodeURIComponent(f.url.replace(f.baseUrl, ''));
                    });
                    // 处理path
                    for (let i = 0; i < file.length; i++) {
                        file[i].path = file[i].url.replace(file[i].baseUrl, '');
                    }
                    let parentDocument = parent.$(window.parent.document)
                    let preview = parentDocument.find(targetId + '-preview')
                    if (!isMulti) {
                        preview.empty()
                        switch (setAttr){
                            case 'text':
                                parentDocument.find(targetId).focus().text(urls.join(',')).trigger('change').trigger('input');
                                break;
                            default:
                                parentDocument.find(targetId).focus().val(urls.join(',')).trigger('change').trigger('input');
                        }
                    } else {
                        // 读取本地再添加文件
                        let existUrls = parentDocument.find(targetId).val() ?? ''
                        if (existUrls) {
                            existUrls = existUrls + ','
                        }
                        switch (setAttr){
                            case 'text':
                                parentDocument.find(targetId).focus().text(existUrls + urls.join(',')).trigger('change').trigger('input');
                                break;
                            default:
                                parentDocument.find(targetId).focus().val(existUrls + urls.join(',')).trigger('change').trigger('input');
                        }
                    }
                    parentDocument.find(targetId).trigger('input').trigger('change')
                    if (parentDocument.find(targetId + '-close-modal').length > 0) {
                        parentDocument.find(targetId + '-close-modal').click()
                    }
                    for (var i = 0; i < file.length; i++) {
                        let f = file[i]
                        let fileJson = JSON.stringify(f).escapeString()
                        var wrapper = document.createElement('div');
                        wrapper.innerHTML = `<div class="drag-item" draggable="true">
                                                        <div class="close" onclick="delSelectedImage(event)">x</div>
                                                        <img data-src="${f.path}" src="${f.tmb}" alt="${f.name}" class="drag-pic img-responsive" draggable="false" data-file="${fileJson}">
                                                    </div>`;
                        var html = wrapper.firstChild;
                        preview.append(html)
                    }
                    if (closeId !== undefined) {
                        parentDocument.find(closeId).click()
                    }
                },
                // bootCalback calls at before elFinder boot up
                bootCallback: function (fm, extraObj) {
                    /* any bind functions etc. */
                    fm.bind('init', function () {
                        // any your code
                    });
                    // for example set document.title dynamically.
                    var title = document.title;
                    fm.bind('open', function () {
                        var path = '',
                            cwd = fm.cwd();
                        if (cwd) {
                            path = fm.path(cwd.hash) || null;
                        }
                        document.title = path ? path + ':' + title : title;
                    }).bind('destroy', function () {
                        document.title = title;
                    });
                }
            },
            managers: {
                // 'DOM Element ID': { /* elFinder options of this DOM Element */ }
                'elfinder': {}
            },
        });
    </script>
</head>
<body>

<!-- Element where elFinder will be created (REQUIRED) -->
<div id="elfinder"></div>

</body>
</html>
